package com.chongyahhh.security.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.chongyahhh.security.bean.model.BaseResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author chongyahhh
 * 登录成功后的处理
 */
public class JsonAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final String LOGIN_SUCCESS = "登陆成功";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 如果输出流没有关闭，统一返回 登陆成功
        if(!response.isCommitted()){
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(LOGIN_SUCCESS, false, null)));
        }
    }
}
